/*
 * Copyright 2016-2017 TVI Go Easy.
 * Created on 2017/4/24 12:20
 */
package org.mechanic.fund.service.product.impl;

import org.mechanic.core.Constants;
import org.mechanic.fund.domain.product.ProductStatus;
import org.mechanic.fund.domain.utils.mapper.DtoBeanMapper;
import org.mechanic.fund.repository.product.ProductStatusRepository;
import org.mechanic.fund.service.product.IProductStatusService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.domain.Sort.Order;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 募集状态服务实现
 *
 * @author mechanic
 * @version 0.0.1
 */
@Service
public class ProductStatusService implements IProductStatusService {

    private static Logger logger = LoggerFactory.getLogger(ProductStatusService.class);

    private ProductStatusRepository productStatusRepository;

    @Autowired
    public ProductStatusService(ProductStatusRepository productStatusRepository) {
        this.productStatusRepository = productStatusRepository;
    }

    /**
     * 返回按sort字段升序排序的募集状态列表
     *
     * @return 募集状态列表
     */
    @Override
    @Cacheable(value = Constants.EHCACHE_NAME)
    public List<ProductStatus> getProductStatusList() {
        Order order = new Order(Direction.ASC, "sort");
        Sort sort = new Sort(order);
        return (List<ProductStatus>) this.productStatusRepository.findAll(sort);
    }

    /**
     * 返回匹配指定主键编号的对象
     *
     * @param id 主键编号
     * @return 对象实体
     */
    @Override
    @Cacheable(value = Constants.EHCACHE_NAME)
    public ProductStatus getById(String id) {
        return this.productStatusRepository.findOne(id);
    }

    /**
     * 保存。 主键为空则create，不为空则update。
     *
     * @param productStatuses 被保存的对象
     */
    @Override
    public void save(List<ProductStatus> productStatuses, String operationUserId) {
        this.productStatusRepository.save(DtoBeanMapper.setOperationToList(productStatuses, operationUserId));
    }

    /**
     * 删除匹配主键ID的对象
     *
     * @param id 主键ID
     */
    @Override
    public void delete(String id) {
        try {
            this.productStatusRepository.delete(id);
        } catch (EmptyResultDataAccessException e) {
            logger.info(id + "不存在");
        }
    }
}
